<template>
  <div class="app-container">

    <el-form :model="param" :inline="true" label-width="68px">
      <el-form-item style="width:320px">
        <div>箱号</div>
        <MultipleBoxNumbersDialog v-model="param.containerNo" clearable/>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>订单号</div>
        <el-input v-model.trim="param.orderNo" placeholder="请输入" clearable> </el-input>
      </el-form-item>
      <el-form-item style="width:300px">
        <div>提箱日期</div>
        <el-date-picker v-model="param.planPickupDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" clearable/>
      </el-form-item>
      <el-form-item style="width:300px">
        <div>还箱日期</div>
        <el-date-picker v-model="param.returnDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" clearable/>
      </el-form-item>
      <el-form-item style="width:300px">
        <div>客户</div>
        <!-- <el-select v-model="param.createDate" /> -->
        <el-input v-model.trim="param.agentName" placeholder="请输入" clearable> </el-input>
      </el-form-item>
      <el-form-item style="width:300px">
        <div>发票状态</div>
        <el-select v-model="param.invoiceStatus" clearable style="width:100%" placeholder="请选择">
          <el-option v-for="item in DATA_invoiceStatuss" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item  style="width:150px">
        <div>箱源</div>
         <el-select v-model="param.containerClassify" clearable style="width: 100%;" placeholder="请选择箱源">
              <el-option
                  v-for="item in dictList.containerClassifyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item style="width:300px">
        <div>集装箱公司</div>
        <el-input v-model.trim="param.outBoxCompanyName" placeholder="请输入" clearable> </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReSet" :icon="Refresh" style="margin-top: 30px">重置</el-button>
        <el-button @click="getTableData" :icon="Search" type="primary" style="margin-top: 30px">查询</el-button>
      </el-form-item>
    </el-form>

    <div>
      <cz-tages :bottomLine="true" :typeList="param.typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
      <span style="margin-top: -40px;float: right;">
        <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有集装箱" placement="left">
          <template v-if="isSelectAll">
            <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
          </template>
          <template v-else>
              <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
          </template>
        </el-tooltip>
        <el-button type="primary" size="small" round @click="toExportExcelData" plain>导出</el-button>
        <el-button type="primary" size="small" :disabled="!selection.length" round @click="applyInvoice"
          plain>申请发票</el-button>
      </span>
      <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" @pageChange="onTablePageChange" @applyInvoice="applyInvoice" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox"></Table>
    </div>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible">
      <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>发票信息
      </div>
      <div style="height:180px;overflow: auto;margin-bottom: 10px">
        <invoice-template></invoice-template>
      </div>
      <el-form inline label-position="left" style="color: black;margin-bottom: 10px">
        <el-form-item label="发票状态:"><span style="color: green;">{{ '待开票' }}</span></el-form-item>
        <el-form-item label="发票内容:">{{ '明细' }}</el-form-item>
        <el-form-item label="发票抬头:">{{ '企业' }}</el-form-item>
        <el-form-item label="联系电话:">{{ }}</el-form-item>
        <el-form-item label="在线咨询">
          <el-button type="primary" size="large" style="font-size: 15px;" link icon="ChatDotRound"></el-button>
        </el-form-item>
      </el-form>
      <div style="border:none;border-top: 1px solid #a6a9ad;padding: 10px 0 10px 0;">
        <el-form label-width="140px" label-position="left">
          <el-form-item label="发票类型">
            <el-radio-group v-model="param.invoiceType">
              <el-radio v-for="item in param.invoiceTypeList" :value="item.value" :key="item.value"
                :label="item.label"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="企业名称">
            <el-input v-model="param.invoiceTitle" style="width: 400px;" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="统一社会信用代码">
            <el-input v-model="param.creditCode" style="width: 400px;" placeholder="请输入统一社会信用代码"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <el-form inline>
        <el-form-item label="应付箱量：">{{ tableRef.multipleSelection.length }} 个</el-form-item>
        <el-form-item label="应扣超期费总计：">$ {{ param.needMinus }} </el-form-item>
        <el-form-item label="应付箱贴费总计：">$ {{ param.needPay }} </el-form-item>
        <el-form-item label="减免超期费总计：">$
          <el-input v-model="param.jianMian" style="width: 100px;" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>

      <el-form inline>
        <el-form-item label="实扣其他费总计：">$
          <el-input v-model="param.deductElseAmount" style="width: 100px;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="实扣超期费总计：">$ {{ realMinus }} </el-form-item>
        <el-form-item label="实付箱贴费总计：">$ {{ realPay }}</el-form-item>
        <!-- <el-form-item label="结算币种：">
          <el-radio-group v-model="param.radio1">
            <el-radio value="1" size="large">￥</el-radio>
            <el-radio value="2" size="large">$</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <el-table :data="tableRef.multipleSelection" style="width: 100%;">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="containerNo" label="箱号" width="180"></el-table-column>
        <el-table-column label="箱型" width="180">
          <template v-slot="scope">
            {{ { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }[scope.row.boxType] }}
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="箱贴费（$）"></el-table-column>
        <el-table-column prop="overdueDays" label="超期天数"></el-table-column>
        <el-table-column prop="overdueAmount" label="超期费（$）"></el-table-column>
        <el-table-column prop="dealAmount" label="应付箱贴费（$）"></el-table-column>
      </el-table>

      <div style="text-align: center;margin-top: 20px;">
        <el-checkbox v-model="param.radio">勾选后即同意买方应当在卖方开具发票之日起合理期间内支付货款</el-checkbox>
        <div class="dialog-footer">
          <el-button @click="param.dialogVisible = false">取消</el-button>
          <el-button @click="handleApplyInvoice" type="primary">确认</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import { getInvoicesInfo, addCallbackRequestInvoice } from '@/api/invoice/index'
import {agentOrderDealWithPage, exportBoxEastReturnBox} from '@/api/boxCallBack/order'
import invoiceTemplate from '@/views/components/invoiceTemplate'
import { numAdd, numSub, numMulti } from '@/utils/compute'
import { computed, onActivated, onMounted, reactive, ref } from 'vue';
import {
  Plus,
  Delete,
  Promotion,
  Edit,
  Message,
  Download,
  ChatDotRound
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog.vue'
import {formatContainerNo} from '@/utils/mlpBox' // 格式化箱号
import {DATA_invoiceStatuss} from '@/data/invoice.js'
import dictList from '@/utils/dictList'
import {downloadFile} from '@/utils/download'
const param = reactive({
  radio: 0,
  loading: false,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  invoiceStatusFilter: { 5: '未申请', 10: '待开票', 15: '已开票',20: '待红冲', 25: '已红冲' }, // 发票状态
  stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  boxTypeOptions: [
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
   { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提', },
    { value: '5', label: '全新', },
  ],
  beginTotalRentQty: '',
  endTotalRentQty: '',
  boxBackCity: '',
  boxStartCity: '',
  startCityOptions: [],
  backCityOptions: [],
  typeList: [],
  deductElseAmount: 0,
  containerClassify:'',
  outBoxCompanyName:'',
  jianMian: 0,
  invoiceStatus:"",
  invoiceType: 5,
  invoiceTypeList: [{ value: 5, label: '增值税普通发票' }, { value: 10, label: '增值税专用发票' }],
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    // { key: 'releaseRentId', colWidth: '220', title: 'releaseRentId', type: 'text', isCheck: true },
    // { key: 'id', colWidth: '220', title: 'ID', type: 'text', isCheck: true },
    { key: 'containerNo', colWidth: '200', title: '箱号', type: 'text', isCheck: true },
    { key: 'boxType', colWidth: '120', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'unitPrice', colWidth: '100', title: '箱贴费', type: 'add',currency:'priceCurrency', before: '$', isCheck: true },
    { key: 'containerClassify', colWidth: '100', title: '箱源', type: 'filter', filter: { 5: '自有', 10: '代管', 15: '外调'}, isCheck: true },
    { key: 'outBoxCompanyName', colWidth: '200', title: '集装箱公司', type: 'text', isCheck: true },
    { key: 'agentName', colWidth: '200', title: '客户', type: 'text', isCheck: true },
    { key: 'createTime', colWidth: '200', title: '提箱日期', type: 'date', isCheck: true },
    { key: 'returnDate', colWidth: '200', title: '还箱日期', type: 'date', isCheck: true },
    { key: 'returnCityName', colWidth: '160', title: '还箱城市', type: 'text', isCheck: true },
    { key: 'boxUsagePeriod', colWidth: '120', title: '用箱天数', type: 'add', after: '天', isCheck: true },
    { key: 'overdueDays', colWidth: '120', title: '超期天数', type: 'add', after: '天', isCheck: true },
    { key: 'overdueAmount', colWidth: '120', title: '超期费', type: 'add', before: '$', isCheck: true },
    { key: 'invoiceStatus', colWidth: '120', title: '发票状态', type: 'filter', filter: param.invoiceStatusFilter, cFilter: param.stateColor, isCheck: true },
    { key: 'orderNo', colWidth: '200', title: '订单号', type: 'text', isCheck: true, fixed: 'right', },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

function handleTypeChange(val: any) {
  param.status = val
  getTableData()
}

function getTableData() {
  const { container, containerList } = formatContainerNo(param.containerNo);
  let data = {
    containerNo: container, // 单箱号查询
    containerNos: containerList, // 多箱号查询
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    orderNo: param.orderNo,
    agentName: param.agentName,
    containerClassify:param.containerClassify,
    outBoxCompanyName:param.outBoxCompanyName,
    invoiceStatus:param.invoiceStatus
  };
  if (param.returnDate) {
    data.beginReturnDate = param.returnDate[0]
    data.endReturnDate = param.returnDate[1]
  }
  if (param.planPickupDate) {
    data.beginPlanPickupDate = param.planPickupDate[0]
    data.endPlanPickupDate = param.planPickupDate[1]
  }
  table.config.loading = true;
  // 获取列表数据
  agentOrderDealWithPage(data).then((res: any) => {
    table.data = JSON.parse(JSON.stringify(res.data.list));
    table.config.total = res.data.total;
  });
  table.config.loading = false;
}
// 重置
function handleReSet() {
  param.containerNo = null
  param.orderNo = null
  param.planPickupDate = null
  param.returnDate = null
  param.agentName = null
  param.invoiceStatus = null
  param.containerClassify = null
  param.outBoxCompanyName = null
  getTableData()
}

//上架/下架  
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})

//申请发票  
const applyInvoice = () => {
  if (selection.value.length == 0) {
    ElMessage.warning('请选择操作对象！')
    return
  }
  param.needMinus = needMinus()
  param.needPay = needPay()
  // param.realMinus = numSub(param.needMinus - 0, param.jianMian - 0)
  // param.realPay = numSub(param.needPay - 0, param.deductElseAmount - 0)
  tableRef.value.multipleSelection.forEach((item: any) => {
    item.dealAmount = (item.unitPrice - 0) - (item.overdueAmount - 0)
  })
  // getInvoicesInfo().then((res: any) => {
  // })
  param.dialogVisible = true;
};
const handleApplyInvoice = () => {
  if (!param.radio) {
    ElMessage.warning('请勾选 提示信息！')
    return
  }
  const invoiceOrder: any = []
  const callbackOrderId: any = []
  const containerIds: any = []
  const containerNoDetail: any = []
  tableRef.value.multipleSelection.forEach((item: any) => {
    invoiceOrder.push({ "orderId": item.orderId, "orderNo": item.orderNo })
    callbackOrderId.push(item.orderId)
    containerIds.push(item.id)
    containerNoDetail.push({
      "containerNo": item.containerNo, "boxType": item.boxType, "unitPrice": item.unitPrice, "overdueDays": item.overdueDays, "overdueAmount": item.overdueAmount, "dealAmount": 10
    })
  })
  // console.log(invoiceOrder)
  // console.log(callbackOrderId)
  // data = {
  //   "containerIds": [1814237410068332547],
  //   "invoiceOrder": "[{\"orderId\": 1814240791595909123,\"orderNo\": \"ZLOID2024080709676097\"},{\"orderId\": 1814240791595909122,\"orderNo\": \"ZLOID2024080630372663\"}]",
  //   "invoiceType": 5,
  //   "invoiceTitle": "发票抬头企业名称",
  //   "annulOverdueAmount": 0,
  //   "deductElseAmount": 0,
  //   "invoiceContent": "回调箱明细",
  //   "creditCode": "9464511851RFG1385D"
  // }

  const data = {
    "containerIds": containerIds,
    "invoiceOrder": JSON.stringify(invoiceOrder),
    // "containerNoDetail": JSON.stringify(containerNoDetail),
    "invoiceType": param.invoiceType,
    "invoiceTitle": param.invoiceTitle,
    "annulOverdueAmount": param.jianMian, //减免超期费
    deductElseAmount: param.deductElseAmount, //实扣其他费总计
    // "paymentOverdueAmount": realMinus.value, //实扣超期费
    // "deductAmount": realPay.value, //实付箱贴费

    "invoiceContent": "回调箱明细jc测试",
    "creditCode": param.creditCode,
  }
  console.log(data)
  addCallbackRequestInvoice(data).then((res: any) => {
    ElMessage.success('申请已提交！')
    getTableData()
  })
  // deletePitch(ids).then((res: any) => {
  //   getTableData()
  // })
  param.dialogVisible = false;
};


//计算 numAdd, numSub, numMulti
//应扣超期费总计
function needMinus() {
  let sum = 0
  tableRef.value.multipleSelection.forEach((item: any) => {
    if (!item.overdueAmount) return
    sum = numAdd(sum, item.overdueAmount - 0)
  })
  return sum
}

//应付箱贴费总计
function needPay() {
  let sum = 0
  tableRef.value.multipleSelection.forEach((item: any) => {
    if (!item.unitPrice) return
    sum = numAdd(sum, item.unitPrice - 0)
  })
  return sum
}

const realMinus = computed(() => {
  return numSub(param.needMinus - 0, param.jianMian - 0)
})
const realPay = computed(() => {
  return numSub(param.needPay - 0, param.deductElseAmount - 0)
})

//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

onActivated(() => {
  getTableData()
})

const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const slectAll = async(val:any) =>{
    checkAll.value = []
    await agentOrderDealWithPage({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}


// 列表导出
const toExportExcelData = () => {
  let checkAllItem = []
  if (isSelectAll.value) {
    checkAllItem = tableRef.value.multipleSelection
  } else {
    checkAllItem = allId.value
  }
  const ids = checkAllItem.map((item: any) => item.id)
  if (ids.length < 1) return ElMessage.warning('请选择要导出的进口应付数据！')
  ElMessageBox.confirm('确认要导出选中的进口应付数据', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let reqParam = {"returnBoxListDetailIds": ids}
    exportBoxEastReturnBox(reqParam).then((res: any) => {
      downloadFile(res, '进口应付信息')
    }).catch((error: any) => {
      ElMessage.error(error)
    })
  }).catch(() => {
  });
}

</script>

<style scoped></style>